import { useState, useEffect, useRef } from 'react'
import { Form, message } from 'antd'
import { useNavigate } from 'react-router-dom'
import { pageType, IResource, IResourceList } from '../type'
import { getResourceHandle, uploadHandle, downLoad, deleteResource, view } from '../service'
import { isNullData, exportData } from '@/utils'

export default (): IResource => {
  const ceshidiv = useRef<any>(null)
  const navigate = useNavigate()
  const [tableList, setTableList] = useState<IResourceList[]>([])
  // 筛选form
  const [filterForm] = Form.useForm()

  // 分页信息
  const [pageParams, setPageParams] = useState<pageType>({
    totalCount: 0,
    pageIndex: 1,
    pageSize: 10,
  })

  // 筛选
  const [filter, setFilter] = useState<{ name: string }>({
    name: '',
  })

  // 更换页码
  const handleChangePage = async (page: number, pageSize?: number) => {
    await setPageParams((v) => ({
      ...v,
      pageIndex: page,
      pageSize: pageSize || pageParams.pageSize,
    }))
  }

  // 标题搜索回调
  const titleSearch = (e: { target: { value: string } }) => {
    setFilter({ ...filter, name: e.target.value })
  }

  // 获取资源列表
  const getList = async () => {
    const params = {
      pageIndex: pageParams.pageIndex,
      pageSize: pageParams.pageSize,
      search: {
        name: filter.name,
      },
    }
    const res = await getResourceHandle(params)
    if (isNullData(res) && res.data) {
      setTableList(res.data?.items.map((item) => ({ ...item, type: item.name.split('.')[1] })))
      setPageParams({ ...pageParams, totalCount: res.data?.totalCount })
    }
  }

  // 上传
  const handleFileUpload = async (file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    try {
      const response = await uploadHandle(formData)
      if (isNullData(response) && response.data) {
        message.success('文件导入成功！')
        getList()
      }
      // 处理上传成功的逻辑
    } catch (error) {
      // 处理上传失败的逻辑
      console.error(error)
      message.error('导入失败，请重试！')
    }
  }

  // 下载
  const getFile = async (record: IResourceList) => {
    const realName = record.address.split('/')[1]
    const params = {
      path: 'uploadFile',
      imageNames: [realName],
      originalFileName: record.name,
      id: record.id,
    }
    const res = await downLoad(params)
    if (res) {
      exportData(res, record.name, realName.split('.')[1])
      await getList()
    }
  }

  // 选择文件
  const handleUpload = (info: any) => {
    if (info.file.status === 'done') {
      handleFileUpload(info.file.originFileObj)
    } else if (info.file.status === 'error') {
      message.error('文件导入失败！')
    }
  }

  // 删除文件
  const deleteHandle = async (record: IResourceList) => {
    const params = {
      path: 'uploadFile',
      imageNames: [record.address.split('/')[1]],
      id: record.id,
    }
    const res = await deleteResource(params)
    if (isNullData(res)) {
      message.success('删除成功')
      await getList()
    }
  }

  // 查看回调
  const viewHandle = async (record: IResourceList) => {
    console.log('record🚀🚀🚀🚀', record)
    const params = {
      path: 'uploadFile',
      imageName: record.address.split('/')[1],
      originalFileName: record.name,
      id: record.id,
    }
    const res = await view(params)
    navigate('/resource-zone/preview', { state: { url: res, ...record } })

    if (res) {
      await getList()
    }
  }

  // 初始化
  const init = async () => {
    getList()
  }

  useEffect(() => {
    init()
  }, [filter, pageParams.pageIndex, pageParams.pageSize])

  return {
    tableList,
    filterForm,
    titleSearch,
    handleChangePage,
    pageParams,
    handleFileUpload,
    handleUpload,
    getFile,
    deleteHandle,
    viewHandle,
    ceshidiv,
  }
}
